package com.vehiclemanagement.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vehiclemanagement.entity.ETCCard;
import com.vehiclemanagement.entity.ETCPassage;
import com.vehiclemanagement.mapper.ETCCardMapper;
import com.vehiclemanagement.mapper.ETCPassageMapper;
import com.vehiclemanagement.service.ETCPassageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.Year;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * ETC通行记录服务实现类
 */
@Service
public class ETCPassageServiceImpl extends ServiceImpl<ETCPassageMapper, ETCPassage> implements ETCPassageService {

    @Autowired
    private ETCPassageMapper etcPassageMapper;
    
    @Autowired
    private ETCCardMapper etcCardMapper;

    @Override
    public IPage<ETCPassage> pagePassages(Integer current, Integer size, String searchTerm, 
                                        Long vehicleId, Long etcCardId, Integer passageType, Integer status,
                                        LocalDateTime startTime, LocalDateTime endTime) {
        // 创建分页对象
        Page<ETCPassage> page = new Page<>(current, size);
        
        // 创建自定义SQL条件
        String whereSql = " p.del_flag = 0 ";
        
        // 添加搜索条件
        if (StringUtils.isNotBlank(searchTerm)) {
            whereSql += " AND (v.plate_number LIKE '%" + searchTerm + "%' OR p.entry_station LIKE '%" + searchTerm + "%' " +
                    "OR p.exit_station LIKE '%" + searchTerm + "%' OR e.card_number LIKE '%" + searchTerm + "%') ";
        }
        
        // 添加车辆ID查询条件
        if (vehicleId != null) {
            whereSql += " AND p.vehicle_id = " + vehicleId;
        }
        
        // 添加ETC卡ID查询条件
        if (etcCardId != null) {
            whereSql += " AND p.etc_card_id = " + etcCardId;
        }
        
        // 添加通行类型查询条件
        if (passageType != null) {
            whereSql += " AND p.passage_type = " + passageType;
        }
        
        // 添加状态查询条件
        if (status != null) {
            whereSql += " AND p.status = " + status;
        }
        
        // 添加时间范围查询条件
        if (startTime != null) {
            whereSql += " AND p.exit_time >= '" + startTime + "'";
        }
        
        if (endTime != null) {
            whereSql += " AND p.exit_time <= '" + endTime + "'";
        }
        
        // 添加排序
        whereSql += " ORDER BY p.exit_time DESC";
        
        System.out.println("执行查询SQL条件: " + whereSql);
        
        // 执行查询
        return etcPassageMapper.selectPageWithInfo(page, whereSql);
    }

    @Override
    public ETCPassage getPassageById(Long id) {
        return etcPassageMapper.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addPassage(ETCPassage passage) {
        System.out.println("服务层开始添加ETC通行记录: " + passage);
        
        try {
            // 设置默认值
            if (passage.getExitTime() == null) {
                passage.setExitTime(LocalDateTime.now());
            }
            if (passage.getCreateTime() == null) {
                passage.setCreateTime(LocalDateTime.now());
            }
            if (passage.getUpdateTime() == null) {
                passage.setUpdateTime(LocalDateTime.now());
            }
            if (passage.getDelFlag() == null) {
                passage.setDelFlag(0);
            }
            if (passage.getStatus() == null) {
                passage.setStatus(1); // 默认为已创建状态
            }
            
            // 先插入通行记录
            int result = etcPassageMapper.insert(passage);
            
            if (result > 0 && passage.getStatus() == 2) { // 如果是已结算状态，则更新ETC卡余额
                // 更新ETC卡余额
                if (passage.getEtcCardId() != null && passage.getFee() != null) {
                    updateETCCardBalance(passage.getEtcCardId(), passage.getFee());
                }
            }
            
            System.out.println("插入结果: " + result + ", 生成的ID: " + passage.getId());
            
            return result > 0;
        } catch (Exception e) {
            System.err.println("添加ETC通行记录发生异常: " + e.getMessage());
            e.printStackTrace();
            throw e; // 抛出异常以触发事务回滚
        }
    }

    @Override
    public boolean updatePassage(ETCPassage passage) {
        // 更新时间
        passage.setUpdateTime(LocalDateTime.now());
        
        return etcPassageMapper.updateById(passage) > 0;
    }

    @Override
    public boolean deletePassage(Long id) {
        // 使用物理删除
        System.out.println("执行物理删除ETC通行记录，ID: " + id);
        
        try {
            // 直接物理删除记录
            int result = etcPassageMapper.deletePhysically(id);
            System.out.println("物理删除结果: " + result);
            return result > 0;
        } catch (Exception e) {
            System.err.println("删除ETC通行记录时出错: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean settlePassage(Long id) {
        System.out.println("结算ETC通行记录，ID: " + id);
        
        try {
            // 查询通行记录
            ETCPassage passage = etcPassageMapper.selectById(id);
            if (passage == null) {
                System.err.println("找不到指定的ETC通行记录，ID: " + id);
                return false;
            }
            
            // 已结算的记录不重复结算
            if (passage.getStatus() == 2) {
                System.out.println("该ETC通行记录已结算，无需重复结算，ID: " + id);
                return true;
            }
            
            // 更新状态为已结算
            passage.setStatus(2);
            passage.setUpdateTime(LocalDateTime.now());
            
            boolean updateResult = updatePassage(passage);
            
            if (updateResult) {
                // 扣减ETC卡余额
                if (passage.getEtcCardId() != null && passage.getFee() != null) {
                    updateETCCardBalance(passage.getEtcCardId(), passage.getFee());
                }
            }
            
            return updateResult;
        } catch (Exception e) {
            System.err.println("结算ETC通行记录发生异常: " + e.getMessage());
            e.printStackTrace();
            throw e; // 抛出异常以触发事务回滚
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchSettlePassages(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return 0;
        }
        
        System.out.println("批量结算ETC通行记录，ID列表: " + ids);
        
        // 记录成功结算的记录数
        int successCount = 0;
        
        for (Long id : ids) {
            try {
                boolean success = settlePassage(id);
                if (success) {
                    successCount++;
                }
            } catch (Exception e) {
                System.err.println("结算ETC通行记录ID: " + id + " 失败: " + e.getMessage());
                // 继续处理下一条记录
            }
        }
        
        return successCount;
    }

    /**
     * 更新ETC卡余额
     */
    private void updateETCCardBalance(Long etcCardId, BigDecimal fee) {
        ETCCard etcCard = etcCardMapper.selectById(etcCardId);
        if (etcCard != null) {
            // 扣减余额
            BigDecimal newBalance = etcCard.getBalance().subtract(fee);
            // 余额不能为负
            if (newBalance.compareTo(BigDecimal.ZERO) < 0) {
                newBalance = BigDecimal.ZERO;
            }
            etcCard.setBalance(newBalance);
            etcCard.setUpdateTime(LocalDateTime.now());
            
            etcCardMapper.updateById(etcCard);
            System.out.println("更新ETC卡余额成功，卡号: " + etcCard.getCardNumber() + ", 新余额: " + newBalance);
        }
    }

    @Override
    public BigDecimal sumFeeByVehicleId(Long vehicleId) {
        return etcPassageMapper.sumFeeByVehicleId(vehicleId);
    }

    @Override
    public BigDecimal sumFeeByEtcCardId(Long etcCardId) {
        return etcPassageMapper.sumFeeByEtcCardId(etcCardId);
    }

    @Override
    public List<Map<String, Object>> statisticsByMonth(Integer year) {
        if (year == null) {
            year = Year.now().getValue();
        }
        
        LocalDateTime startTime = LocalDateTime.of(year, 1, 1, 0, 0, 0);
        LocalDateTime endTime = LocalDateTime.of(year, 12, 31, 23, 59, 59);
        
        return etcPassageMapper.statisticsByMonth(startTime, endTime);
    }

    @Override
    public List<Map<String, Object>> statisticsByPassageType(LocalDateTime startTime, LocalDateTime endTime) {
        if (startTime == null) {
            startTime = LocalDateTime.of(Year.now().getValue(), 1, 1, 0, 0, 0);
        }
        
        if (endTime == null) {
            endTime = LocalDateTime.of(Year.now().getValue(), 12, 31, 23, 59, 59);
        }
        
        return etcPassageMapper.statisticsByPassageType(startTime, endTime);
    }
} 